'use client';

import useToast from '@/hooks/useToast';
import { useMutation } from '@tanstack/react-query';
import { logout } from '@/services/api';
import { type MouseEvent } from 'react';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function LogoutDropdownItem({
  translatedFields,
}: {
  translatedFields: PrefixedTTranslatedFields<'navbar'>;
}) {
  const { show } = useToast();

  const logoutMutation = useMutation(logout);

  async function onClickLogout(e: MouseEvent<HTMLAnchorElement>) {
    try {
      e.stopPropagation();
      e.preventDefault();

      await logoutMutation.mutateAsync({});

      show({
        type: 'SUCCESS',
        message: translatedFields.logoutComplete,
      });

      setTimeout(() => {
        show({
          type: 'INFO',
          message: translatedFields.reloadSoon,
        });
      }, 1000);

      setTimeout(() => {
        if (
          location.href.includes('/admin') ||
          location.href.includes('/new') ||
          location.href.includes('/edit')
        ) {
          location.href = '/';
        } else {
          location.reload();
        }
      }, 1500);
    } catch (e) {
      logoutMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  return (
    <li>
      <a onClick={onClickLogout} className="dropdown-item cursor-pointer">
        {translatedFields.logout}
      </a>
    </li>
  );
}
